# -*- coding:utf-8 -*-

import os
from fastapi import APIRouter, Depends, UploadFile, File, Request, HTTPException
from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession

from config.get_db import get_db
from config.enums import BusinessType
from module_admin.annotation.log_annotation import Log
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.agent_file_service import AgentFileService
from module_admin.service.login_service import LoginService
from utils.response_util import ResponseUtil
from utils.log_util import logger


agent_file_controller = APIRouter(prefix='/agent-files', tags=['Agent文件管理'])


@agent_file_controller.post('/upload')
@Log(title='Agent文件上传', business_type=BusinessType.IMPORT)
async def upload_agent_file(
    request: Request,
    file: UploadFile = File(..., description='Agent压缩包'),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    上传Agent文件到服务器（简化版：只验证IP，无token）
    """
    try:
        result = await AgentFileService.upload_agent_file(db, file)
        result_dict = result.dict() if hasattr(result, 'dict') else result.model_dump()
        return ResponseUtil.success(data=result_dict, msg='文件上传成功')
    except Exception as e:
        logger.error(f"上传Agent文件失败: {e}")
        return ResponseUtil.error(msg=f'文件上传失败: {str(e)}')


@agent_file_controller.get('/download/{filename}')
async def download_agent_file(
    filename: str,
    request: Request,
    db: AsyncSession = Depends(get_db)
):
    """
    下载Agent文件（公开访问，只验证IP是否在server_host表中）
    """
    try:
        # 获取请求IP
        client_ip = request.client.host
        
        # 验证IP是否在server_host表中
        is_valid = await AgentFileService.verify_ip_in_server_hosts(db, client_ip)
        if not is_valid:
            raise HTTPException(status_code=403, detail="无权访问：IP不在授权列表中")
        
        # 获取文件路径
        file_path = AgentFileService.get_file_path(filename)
        
        # 返回文件
        return FileResponse(
            path=file_path,
            filename=filename,
            media_type='application/gzip'
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"下载Agent文件失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))
